package com.sukaiyi.generator.config;

import cn.hutool.json.JSONUtil;
import com.sukaiyi.generator.config.model.StructTemplate;
import com.sukaiyi.generator.config.model.TplType;
import com.sukaiyi.generator.ui.TemplateComboBox;
import com.sukaiyi.generator.ui.TemplateTree;
import com.sukaiyi.generator.ui.base.ConfirmationDialog;
import com.sukaiyi.generator.ui.base.InputDialog;
import com.sukaiyi.generator.utils.IdeaUIUtils;
import com.sukaiyi.generator.utils.ProjectUtils;
import com.sukaiyi.generator.utils.StringUtils;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.JBSplitter;
import icons.PluginIcons;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;

public class TemplateConfigurable implements SearchableConfigurable {

    private final PluginConfig pluginConfig;

    private JPanel rootPanel;
    private JBSplitter splitter;
    private TemplateComboBox templateComBox;
    private JPanel topPanel;
    private TemplateTree tree;
    private EditorTextField editorTextField;
    private StructTemplate currentEditTemplate;

    public TemplateConfigurable(PluginConfig config) {
        pluginConfig = config;
        templateComBox.addItemListener(e -> {
            currentEditTemplate = null;
            StructTemplate template = templateComBox.getSelectedItem();
            tree.setStructTemplate(template);
            splitter.setSecondComponent(new JLabel());
        });
        DefaultActionGroup actionGroup = createActionGroup();
        ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar("Group Toolbar", actionGroup, true);
        topPanel.add(actionToolbar.getComponent());
    }

    private DefaultActionGroup createActionGroup() {
        DefaultActionGroup actionGroup = new DefaultActionGroup();
        actionGroup.add(new AnAction(AllIcons.General.Add) {
            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
                InputDialog dialog = new InputDialog("");
                if (dialog.showAndGet()) {
                    String name = dialog.getValue();
                    StructTemplate template = new StructTemplate();
                    template.setName(name);
                    template.setType(TplType.MODULE);
                    pluginConfig.templates.add(template);
                    templateComBox.updateUI();
                }
            }
        });
        actionGroup.add(new AnAction(AllIcons.Actions.Copy) {
            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
                StructTemplate selected = templateComBox.getSelectedItem();
                InputDialog dialog = new InputDialog(selected.getName() + " Copy");
                if (dialog.showAndGet()) {
                    String name = dialog.getValue();
                    String json = JSONUtil.toJsonStr(selected);
                    StructTemplate newTemplate = JSONUtil.toBean(json, StructTemplate.class);
                    newTemplate.setName(name);
                    pluginConfig.templates.add(newTemplate);
                    templateComBox.updateUI();
                }
            }
        });
        actionGroup.add(new AnAction(AllIcons.General.Remove) {
            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
                StructTemplate selected = templateComBox.getSelectedItem();
                ConfirmationDialog dialog = new ConfirmationDialog();
                if (dialog.showAndGet()) {
                    pluginConfig.templates.remove(selected);
                    templateComBox.updateUI();
                }
            }
        });
        actionGroup.addSeparator();
        actionGroup.add(new AnAction(PluginIcons.PREVIEW) {
            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
            }
        });
        actionGroup.add(new AnAction(AllIcons.Actions.Help) {
            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
            }
        });
        return actionGroup;
    }

    @NotNull
    @Override
    public String getId() {
        return TemplateConfigurable.class.getName();
    }

    @Nls
    @Override
    public String getDisplayName() {
        return "Template";
    }

    @Nullable
    @Override
    public JComponent createComponent() {
        return rootPanel;
    }

    @Override
    public boolean isModified() {
        return true;
    }

    @Override
    public void apply() {
        if (currentEditTemplate != null) {
            String value = editorTextField.getText();
            currentEditTemplate.setContent(value);
        }
        tree.getStructTemplate();
    }

    private void createUIComponents() {
        splitter = new JBSplitter();
        splitter.setProportion(0.3f);
        tree = new TemplateTree();
        tree.setStructTemplate(pluginConfig.templates.get(0));
        tree.addTreeSelectionListener(e -> {
            apply();
            TreePath path = e.getNewLeadSelectionPath();
            if (path == null) {
                return;
            }
            DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) path.getLastPathComponent();
            StructTemplate template = (StructTemplate) treeNode.getUserObject();
            if (template.getType() == TplType.MODULE) {
                return;
            }
            currentEditTemplate = template;
            String suffix = StringUtils.getFileSuffix(template.getName());
            FileType fileType = IdeaUIUtils.getFileTypeByFileSuffix(suffix);
            editorTextField = IdeaUIUtils.createEditorTextField(ProjectUtils.getProject(), fileType);
            editorTextField.setPreferredSize(new Dimension(400, 300));
            Document document = EditorFactory.getInstance().createDocument(template.getContent());
            editorTextField.setDocument(document);
            editorTextField.setCaretPosition(0);
            splitter.setSecondComponent(editorTextField);
        });
        splitter.setFirstComponent(tree.get());
    }
}
